"""
CRUD 操作（Create, Read, Update, Delete）

封装所有数据库操作，提供统一接口
"""

from sqlalchemy.orm import Session
from typing import List, Optional

from . import models, schemas
from .security import hash_password


# ========== 用户 CRUD ==========

def create_user(db: Session, user: schemas.UserCreate) -> models.User:
    """
    创建新用户
    
    Args:
        db: 数据库会话
        user: 用户创建数据
        
    Returns:
        创建的用户对象
    """
    hashed_password = hash_password(user.password)
    
    db_user = models.User(
        username=user.username,
        email=user.email,
        hashed_password=hashed_password,
        full_name=user.full_name,
    )
    
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    
    return db_user


def get_user(db: Session, user_id: int) -> Optional[models.User]:
    """根据 ID 获取用户"""
    return db.query(models.User).filter(models.User.id == user_id).first()


def get_user_by_username(db: Session, username: str) -> Optional[models.User]:
    """根据用户名获取用户"""
    return db.query(models.User).filter(models.User.username == username).first()


def get_user_by_email(db: Session, email: str) -> Optional[models.User]:
    """根据邮箱获取用户"""
    return db.query(models.User).filter(models.User.email == email).first()


def get_users(
    db: Session,
    skip: int = 0,
    limit: int = 100,
    is_active: Optional[bool] = None,
) -> List[models.User]:
    """获取用户列表"""
    query = db.query(models.User)
    
    if is_active is not None:
        query = query.filter(models.User.is_active == is_active)
    
    return query.offset(skip).limit(limit).all()


def update_user(
    db: Session,
    user_id: int,
    user_update: schemas.UserUpdate,
) -> Optional[models.User]:
    """更新用户信息"""
    db_user = get_user(db, user_id)
    if not db_user:
        return None
    
    update_data = user_update.model_dump(exclude_unset=True)
    
    if "password" in update_data:
        update_data["hashed_password"] = hash_password(update_data.pop("password"))
    
    for field, value in update_data.items():
        setattr(db_user, field, value)
    
    db.commit()
    db.refresh(db_user)
    
    return db_user


def delete_user(db: Session, user_id: int) -> bool:
    """删除用户"""
    db_user = get_user(db, user_id)
    if not db_user:
        return False
    
    db.delete(db_user)
    db.commit()
    
    return True


# ========== 文章 CRUD ==========

def create_post(
    db: Session,
    post: schemas.PostCreate,
    author_id: int,
) -> models.Post:
    """创建文章"""
    db_post = models.Post(
        title=post.title,
        content=post.content,
        is_published=post.is_published,
        author_id=author_id,
    )
    
    # 添加标签
    if post.tag_ids:
        tags = db.query(models.Tag).filter(models.Tag.id.in_(post.tag_ids)).all()
        db_post.tags = tags
    
    db.add(db_post)
    db.commit()
    db.refresh(db_post)
    
    return db_post


def get_post(db: Session, post_id: int) -> Optional[models.Post]:
    """获取文章"""
    return db.query(models.Post).filter(models.Post.id == post_id).first()


def get_posts(
    db: Session,
    skip: int = 0,
    limit: int = 100,
    author_id: Optional[int] = None,
    is_published: Optional[bool] = None,
) -> List[models.Post]:
    """获取文章列表"""
    query = db.query(models.Post)
    
    if author_id is not None:
        query = query.filter(models.Post.author_id == author_id)
    
    if is_published is not None:
        query = query.filter(models.Post.is_published == is_published)
    
    return query.offset(skip).limit(limit).all()


def update_post(
    db: Session,
    post_id: int,
    post_update: schemas.PostUpdate,
) -> Optional[models.Post]:
    """更新文章"""
    db_post = get_post(db, post_id)
    if not db_post:
        return None
    
    update_data = post_update.model_dump(exclude_unset=True)
    
    # 处理标签更新
    if "tag_ids" in update_data:
        tag_ids = update_data.pop("tag_ids")
        tags = db.query(models.Tag).filter(models.Tag.id.in_(tag_ids)).all()
        db_post.tags = tags
    
    for field, value in update_data.items():
        setattr(db_post, field, value)
    
    db.commit()
    db.refresh(db_post)
    
    return db_post


def delete_post(db: Session, post_id: int) -> bool:
    """删除文章"""
    db_post = get_post(db, post_id)
    if not db_post:
        return False
    
    db.delete(db_post)
    db.commit()
    
    return True


def increment_post_views(db: Session, post_id: int) -> Optional[models.Post]:
    """增加文章浏览量"""
    db_post = get_post(db, post_id)
    if not db_post:
        return None
    
    db_post.view_count += 1
    db.commit()
    db.refresh(db_post)
    
    return db_post


# ========== 标签 CRUD ==========

def create_tag(db: Session, tag: schemas.TagCreate) -> models.Tag:
    """创建标签"""
    db_tag = models.Tag(
        name=tag.name,
        description=tag.description,
    )
    
    db.add(db_tag)
    db.commit()
    db.refresh(db_tag)
    
    return db_tag


def get_tag(db: Session, tag_id: int) -> Optional[models.Tag]:
    """获取标签"""
    return db.query(models.Tag).filter(models.Tag.id == tag_id).first()


def get_tag_by_name(db: Session, name: str) -> Optional[models.Tag]:
    """根据名称获取标签"""
    return db.query(models.Tag).filter(models.Tag.name == name).first()


def get_tags(db: Session, skip: int = 0, limit: int = 100) -> List[models.Tag]:
    """获取标签列表"""
    return db.query(models.Tag).offset(skip).limit(limit).all()


def delete_tag(db: Session, tag_id: int) -> bool:
    """删除标签"""
    db_tag = get_tag(db, tag_id)
    if not db_tag:
        return False
    
    db.delete(db_tag)
    db.commit()
    
    return True

